package com.mifengs.mall.ui.main;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.LogUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.di.component.DaggerMainComponent;
import com.mifengs.mall.di.module.MainModule;
import com.mifengs.mall.entity.StoreApplyInfo;
import com.mifengs.mall.entity.UpdateData;
import com.mifengs.mall.entity.UpgradeInfo;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.services.DownloadService;
import com.mifengs.mall.services.MqttRecvService;
import com.mifengs.mall.ui.hxcec.ConversationListActivity;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.ui.msg.MsgCenterActivity;
import com.mifengs.mall.ui.my.RedPacketActivity;
import com.mifengs.mall.ui.opencompany.OpenCompanyActivity;
import com.mifengs.mall.ui.openself.OpenSelfActivity;
import com.mifengs.mall.ui.web.WebFragment;
import com.mifengs.mall.util.GPSUtil;
import com.mifengs.mall.util.LocationUtil;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.CircleRecyclerView.HorizontalProgressBar;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, EasyPermissions.PermissionCallbacks, AMapLocationListener {


    @BindView(R.id.img_home)
    ImageView mImgHome;
    @BindView(R.id.txt_home)
    TextView mTxtHome;
    @BindView(R.id.img_classify)
    ImageView mImgClassify;
    @BindView(R.id.txt_classify)
    TextView mTxtClassify;
    @BindView(R.id.img_account)
    ImageView mImgAccount;
    @BindView(R.id.txt_account)
    TextView mTxtAccount;
    @BindView(R.id.img_msg)
    ImageView imgMsg;
    @BindView(R.id.txt_msg)
    TextView txtMsg;
    @BindView(R.id.img_nearby)
    ImageView mImgNearby;
    @BindView(R.id.txt_nearby)
    TextView mTxtNearby;
    @BindView(R.id.iv_my_message)
    ImageView mIvMyMessage;
    private Fragment mConversationFragment;
    private Fragment mHomeFragment;
    private WebFragment mClassifyFragment;
    private WebFragment mAccountFragment;
    private Fragment mCurrentFragment;
    private WebFragment mNearbyFrgament;
    private int mCurrentSelectedIndex;
    private boolean isExit;
    private UpdateData mUpdateData;
    private Dialog mAppUpdateDialog;
    private boolean isPush = false;
    private int msg_appPage;
    private AMapLocationClient mlocationClient;
    private LatLng mLoclatLng;
    private AMapLocation mAmaplocation;
    private  boolean isPermissions= false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        XGPushConfig.enableDebug(this, true);
        ButterKnife.bind(this);
        StatusBarCompat.setStartBarTranslucent(this);
        StatusBarUtils.StatusBarLightMode(this);
        EventBus.getDefault().register(this);
//        mHomeFragment = HomeFragment.newInstance();
        mConversationFragment = ConversationListActivity.newInstance();
        mHomeFragment = NewHomeFragment.newInstance();
        mClassifyFragment = WebFragment.newInstance(Constant.H5_CLASSIFT, "");
        mAccountFragment = WebFragment.newInstance(Constant.H5_MY, "");
        mNearbyFrgament = WebFragment.newInstance(Constant.H5_Nearby+"?lng=&lat=&cityName=", "");
        mClassifyFragment.setStatusBarColor(Color.WHITE);
        mAccountFragment.setStatusBarColor(getResources().getColor(R.color.white));
        mCurrentFragment = mHomeFragment;
        if (savedInstanceState == null) {
            FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            ft.add(R.id.container, mCurrentFragment).commit();
        }
        init();

    }

    @Override
    public void initInjector() {
        DaggerMainComponent.builder()
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    private void init() {
        PreferenceUtils.saveStringPreference(getContext(),"isPermissions","1");
        XGPushConfig.setMiPushAppId(getApplicationContext(), "2882303761517631831");
        XGPushConfig.setMiPushAppKey(getApplicationContext(), "5691763116831");
        XGPushConfig.setHuaweiDebug(true);
        XGPushConfig.enableOtherPush(getApplicationContext(), true);
        XGPushManager.registerPush(getApplicationContext());
        mPresenter.getUpdateInfo();
        mPresenter.getPhotoPath();
        isPush = getIntent().getBooleanExtra("isPush", false);
        if (isPush) {
            setPushMsg();
        }

        if (!Tools.isServiceRunning(getContext(), "com.mifengs.mall.services.MqttRecvService")) {
            startService(new Intent(getContext(), MqttRecvService.class));
//            LogUtil.i("mqtt_mfsc:","mMqttRecvService 停止");
        } else {
//            LogUtil.i("mqtt_mfsc:","mMqttRecvService 正在运行");
            mPresenter.appLaunch();//上线通知
        }

        LogUtil.i("mqtt_t", PreferenceUtils.getToken());
        mPresenter.getUpgradeInfo();
        mPresenter.getSplashInfo();
        needLoc();
    }

    private void setPushMsg() {
        Intent intent = null;
        if (msg_appPage == 1) {
            intent = new Intent(getContext(), MsgCenterActivity.class);
            intent.putExtra("type", 1);
        } else {
            intent = new Intent(getContext(), RedPacketActivity.class);
            intent.putExtra("type", msg_appPage);
        }

        startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        isPush = intent.getBooleanExtra("isPush", false);
        msg_appPage = intent.getIntExtra("msgPage", 0);
        if (isPush) {
            setPushMsg();
        }
    }


    @OnClick({R.id.ll_home, R.id.ll_classify, R.id.ll_account, R.id.ll_msg, R.id.ll_nearby})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_home:
                toHomePage();
                break;
            case R.id.ll_classify:
                toClassifyPage();
                break;
            case R.id.ll_account:
                if (PreferenceUtils.getLoginStatus()) {
                    toAccountPage();
                } else {
                    toLogin();
                }
                break;
            case R.id.ll_msg:
                if (PreferenceUtils.getLoginStatus()) {
                    toMsgPage();
                } else {
                    toLogin();
                }
                break;
            case R.id.ll_nearby:
                toNearbyPage();
                break;
        }
    }


    public void toLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    private void switchContent(Fragment from, Fragment to) {
        if (mCurrentFragment != to) {
            mCurrentFragment = to;
            FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.container, to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
        }
    }

    @Override
    public void toHomePage() {
        if (this.mCurrentSelectedIndex != 0) {
            mCurrentSelectedIndex = 0;
            // Selected
            StatusBarUtils.StatusBarLightMode(this);
            mImgHome.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_home_selected));
            mTxtHome.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_pressed));

            mImgClassify.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_classify_normal));
            mTxtClassify.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            imgMsg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_msg_normal));
            txtMsg.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgAccount.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_account_normal));
            mTxtAccount.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));


            mImgNearby.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_nearby_normal));
            mTxtNearby.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            this.switchContent(mCurrentFragment, mHomeFragment);
        }
    }

    @Override
    public void toClassifyPage() {
        if (this.mCurrentSelectedIndex != 3) {
            mCurrentSelectedIndex = 3;
            // Selected
            StatusBarUtils.StatusBarLightMode(this);
            mImgHome.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_home_normal));
//            mTxtHome.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgClassify.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_classify_selected));
            mTxtClassify.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_pressed));

            imgMsg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_msg_normal));
            txtMsg.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));


            mImgAccount.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_account_normal));
            mTxtAccount.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgNearby.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_nearby_normal));
            mTxtNearby.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            this.switchContent(mCurrentFragment, mClassifyFragment);

        }
    }

    @Override
    public void toMsgPage() {
        if (this.mCurrentSelectedIndex != 2) {
            mCurrentSelectedIndex = 2;
            // Selected
            StatusBarUtils.StatusBarLightMode(this);
            mImgHome.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_home_normal));
//            mTxtHome.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgClassify.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_classify_normal));
            mTxtClassify.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            imgMsg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_msg_selected));
            txtMsg.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_pressed));


            mImgAccount.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_account_normal));
            mTxtAccount.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgNearby.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_nearby_normal));
            mTxtNearby.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            this.switchContent(mCurrentFragment, mConversationFragment);
        }
    }


    @Override
    public void toAccountPage() {
        if (this.mCurrentSelectedIndex != 4) {
            mCurrentSelectedIndex = 4;
            // Selected
            //改变状态栏字体颜色
            StatusBarUtils.StatusBarLightMode(this);
            mImgHome.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_home_normal));
//            mTxtHome.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgClassify.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_classify_normal));
            mTxtClassify.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            imgMsg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_msg_normal));
            txtMsg.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgAccount.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_account_selected));
            mTxtAccount.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_pressed));

            mImgNearby.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_nearby_normal));
            mTxtNearby.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            //mAccountFragment.reloadAccountPage();

            this.switchContent(mCurrentFragment, mAccountFragment);
        }
    }

    @Override
    public void toNearbyPage() {
        if (this.mCurrentSelectedIndex != 1) {
            mCurrentSelectedIndex = 1;
            // Selected
            //改变状态栏字体颜色
            StatusBarUtils.StatusBarLightMode(this);
            mImgHome.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_home_normal));
//            mTxtHome.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgClassify.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_classify_normal));
            mTxtClassify.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            imgMsg.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_msg_normal));
            txtMsg.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgAccount.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_account_normal));
            mTxtAccount.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_normal));

            mImgNearby.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.tab_nearby_selected));
            mTxtNearby.setTextColor(ContextCompat.getColor(this, R.color.bottombar_text_pressed));

            //mAccountFragment.reloadAccountPage();

            this.switchContent(mCurrentFragment,mNearbyFrgament);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainEvent event) {
        switch (event.action) {
            case MainEvent.TOHOMEPAGE:
                toHomePage();
                break;
            case MainEvent.LOGINTRELOAD:  //登录状态的改变
                mIvMyMessage.setVisibility(View.GONE);
                reConnectMqtt();
                if (mAccountFragment != null&&PreferenceUtils.getLoginStatus()) {
                    mAccountFragment.reloadAccountPage();
                }
                break;
            case MainEvent.TOCATEGORY:
                toClassifyPage();
                break;
            case MainEvent.TOMY:
                toAccountPage();
                break;
            case MainEvent.APPLAUNCH:
                mPresenter.appLaunch();//上线通知
                break;
            case MainEvent.OPENSHOP:
                mPresenter.getApplyProgress();
                break;
            case MainEvent.LOGIN:
                startActivity(new Intent(getContext(), LoginActivity.class));
                break;
            case MainEvent.MYMESSAGE:
                int amount = event.getAmount();
                if(amount>0){
                    mIvMyMessage.setVisibility(View.VISIBLE);
                }else{
                    mIvMyMessage.setVisibility(View.GONE);
                }
                break;
        }
    }

    private Button okBtn;

    @Override
    public void showUpdateDialog(UpdateData updateData) {
        this.mUpdateData = updateData;
        mAppUpdateDialog = new Dialog(this, R.style.dialog);
        mAppUpdateDialog.setContentView(R.layout.dialog_update);
        String oldestVersion = updateData.getOldestVersion();
        String nowVerCode = DeviceInfoUtil.getAppVersion(MallApplication.getInstance());

        if (nowVerCode.compareTo(oldestVersion) >= 0) {
            mAppUpdateDialog.setCanceledOnTouchOutside(true);
            (mAppUpdateDialog.findViewById(R.id.bt_cancle)).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mAppUpdateDialog.dismiss();
                }
            });
        } else {
            mAppUpdateDialog.setCanceledOnTouchOutside(false);
            (mAppUpdateDialog.findViewById(R.id.bt_cancle)).setVisibility(View.GONE);
        }
        TextView tvUpdateInfo = (TextView) mAppUpdateDialog.findViewById(R.id.tv_update_info);
        tvUpdateInfo.setText(updateData.getResRemark());
        okBtn = mAppUpdateDialog.findViewById(R.id.bt_update);
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                needDownLoad();
            }

        });

        mAppUpdateDialog.show();

        mAppUpdateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == event.KEYCODE_BACK) {
                    finish();
                } else {
                    return false;
                }
                return false;
            }

        });
        HorizontalProgressBar horizontalProgressBar = new HorizontalProgressBar(getContext());
        for (int i = 0; i < 20; i++) {
            horizontalProgressBar.setCurrentProgress(i);
            horizontalProgressBar.setProgressWithAnimation(i);
        }

    }

    @AfterPermissionGranted(REQUEST_PERMISSION_STORAGE)
    public void needDownLoad() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            isPermissions = true;
            String  isPermissions= PreferenceUtils.getStringPreference(getContext(),"isPermissions");
            if(Integer.parseInt(isPermissions) == 1){
                downLoadApp();
            }
            PreferenceUtils.saveStringPreference(getContext(),"isPermissions","1");
        } else {
            PreferenceUtils.saveStringPreference(getContext(),"isPermissions","0");
            EasyPermissions.requestPermissions(this, "app需要存储权限",
                    REQUEST_PERMISSION_STORAGE, perms);
        }
    }

    private void downLoadApp() {
        if (mUpdateData != null) {
            if (!TextUtils.isEmpty(mUpdateData.getUrl())) {
                Intent intent = new Intent(this, DownloadService.class);
                intent.putExtra("AppUpdateInfo", mUpdateData.getUrl());
                startService(intent);
                okBtn.setText("下载更新中，请耐心等待...");
            }
            okBtn.setEnabled(false);
        }

//        mAppUpdateDialog.dismiss();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mAppUpdateDialog != null) {
            okBtn.setText("更新");
            okBtn.setEnabled(true);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isExit == false) {
                isExit = true;
            } else {
                finish();
            }
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
        EventBus.getDefault().unregister(this);
        super.onDestroy();

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void startShopTypeActivity() {
//        Intent intent = new Intent(getActivity(), ShopTypeActivity.class);
//        startActivity(intent);
        ToIntentUtil.toCommonIntent(Constant.H5_STORE_APPLY_NOTICE, this);
    }

    @Override
    public void upgradeInfo(UpgradeInfo upgradeInfo) {
        Intent intent = new Intent(getContext(),UpgradeInfoActivity.class);
        intent.putExtra("content",upgradeInfo.getContent());
        intent.putExtra("time",upgradeInfo.getDate());
        startActivity(intent);
        finish();
    }


    @Override
    public void startOpenShopActivity(int type, int storeStatus, StoreApplyInfo info) {
        if (type == 0) {
            Intent intent = new Intent(this, OpenSelfActivity.class);
            intent.putExtra("StoreApplyInfo", info);
            startActivity(intent);
        } else if (type == 1) {
            Intent intent = new Intent(this, OpenCompanyActivity.class);
            intent.putExtra("StoreApplyInfo", info);
            startActivity(intent);
        }
    }

    @Override
    public void startLoginActivity() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }


    @AfterPermissionGranted(REQUEST_PERMISSION_LOCATION)
    public void needLoc() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            dingwei();
        } else {
            EasyPermissions.requestPermissions(this, "您需要定位权限",
                    REQUEST_PERMISSION_LOCATION, perms);
        }
    }


    public void dingwei() {
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(getContext());
            mlocationClient.setLocationListener(this);
            AMapLocationClientOption locationOption = LocationUtil.getDefaultOption();
            mlocationClient.setLocationOption(locationOption);
            mlocationClient.startLocation();
        } else {
            mlocationClient.startLocation();
        }
    }


    @Override
    public void onLocationChanged(AMapLocation amaplocation) {
        if (amaplocation != null) {
            if (amaplocation != null && amaplocation.getErrorCode() == 0) {
                this.mAmaplocation = amaplocation;
                mLoclatLng = new LatLng(amaplocation.getLatitude(), amaplocation.getLongitude());
                mlocationClient.stopLocation();

                String url = Constant.H5_Nearby;
                if (mLoclatLng != null && mAmaplocation != null) {
                    double[] doubles = GPSUtil.gcj02_To_Bd09(mLoclatLng.latitude, mLoclatLng.longitude);
                    String city = mAmaplocation.getCity();
                    url = url + "?lng=" + doubles[1] + "&lat=" + doubles[0] + "&cityName=" + city;
                } else {
                    url = url + "?lng=&lat=&cityName=";
                }
                mNearbyFrgament.setPath(url);
            } else {
            }
        }
    }


    private void reConnectMqtt(){
        startService(new Intent(getContext(), MqttRecvService.class));
    }

}

